﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using YArchitech.Revit;

namespace YArchitech.Plumbing
{
	[Regeneration(RegenerationOption.Manual)]
	[Transaction(TransactionMode.Manual)]
	public class FamilyUpdate : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			UIApplication application = commandData.Application;
            Autodesk.Revit.ApplicationServices.Application application2 = application.Application;
			Document document = application.ActiveUIDocument.Document;
			UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
			List<ViewType> list = YJKRevitTools.ListViewNeed(2);
			list.Add((ViewType)115);
			if (!YJKRevitTools.ViewCheck(activeUIDocument, list))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			Result result;
			try
			{
                Autodesk.Revit.DB.View activeView = document.ActiveView;
				transaction = new Transaction(document, "替换族");
				transaction.Start();
				ISelectionFilter selectionFilter = new FamilyInstanceFilter();
				Selection selection = activeUIDocument.Selection;
				Reference reference = selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, selectionFilter, "请选择替换后的新族,即模版族，如事先未布置该族实例，请先布置。");
				Element element = document.GetElement(reference);
				FamilyInstance familyInstance = element as FamilyInstance;
				FormFamilyUpdate formFamilyUpdate = new FormFamilyUpdate();
				DialogResult dialogResult = formFamilyUpdate.ShowDialog();
				if (dialogResult == DialogResult.Yes)
				{
					for (;;)
					{
						try
						{
							Reference reference2 = selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, selectionFilter, "请选择要替换掉的族");
							Element element2 = document.GetElement(reference2);
							FamilyInstance familyInstance2 = element2 as FamilyInstance;
							if (familyInstance2.Host == null && familyInstance.Host != null)
							{
								YJKMessageBox.Show("不能用基于面的去替换非基于面的族！");
								goto IL_1CD;
							}
							if (!formFamilyUpdate.istrue)
							{
								YJKRevitTools.FamilyInstanceReplace(document, familyInstance2, familyInstance);
							}
							else if (formFamilyUpdate.istrue)
							{
								YJKRevitTools.FamilyInstanceReplaces(document, familyInstance2, familyInstance, true);
							}
							continue;
						}
						catch (Autodesk.Revit.Exceptions.OperationCanceledException)
						{
							goto IL_1CD;
						}
						break;
					}
				}
				if (dialogResult == DialogResult.No)
				{
					Reference reference3 = selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, selectionFilter, "请选择要替换掉的族");
					Element element3 = document.GetElement(reference3);
					FamilyInstance familyInstance3 = element3 as FamilyInstance;
					if (familyInstance3.Host == null && familyInstance.Host != null)
					{
						YJKMessageBox.Show("不能用基于面的去替换非基于面的族！");
					}
					else
					{
						List<FamilyInstance> familyInstanceAccordFi = this.GetFamilyInstanceAccordFi(document, familyInstance3);
						foreach (FamilyInstance familyInstance4 in familyInstanceAccordFi)
						{
							FamilyInstance oldFamilyInstance = familyInstance4;
							if (!formFamilyUpdate.istrue)
							{
								YJKRevitTools.FamilyInstanceReplace(document, oldFamilyInstance, familyInstance);
							}
							else if (formFamilyUpdate.istrue)
							{
								YJKRevitTools.FamilyInstanceReplaces(document, oldFamilyInstance, familyInstance, true);
							}
						}
					}
				}
				IL_1CD:
				transaction.Commit();
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
				this.EndTransation(transaction, false);
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				this.EndTransation(transaction, true);
			}
			return result;
		}

		private void EndTransation(Transaction tran, bool beSure)
		{
			if (tran != null)
			{
				TransactionStatus status = tran.GetStatus();
                if ((int)status == 1)
				{
					if (beSure)
					{
						tran.Commit();
						return;
					}
					tran.RollBack();
					return;
				}
                else if ((int)status == 5)
				{
					tran.RollBack();
				}
			}
		}

		public List<FamilyInstance> GetFamilyInstanceAccordFi(Document document, FamilyInstance fiSymbol)
		{
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(document);
			ICollection<Element> collection = filteredElementCollector.OfClass(typeof(FamilyInstance)).ToElements();
			List<FamilyInstance> list = new List<FamilyInstance>();
			foreach (Element element in collection)
			{
				if (element != null && element is FamilyInstance)
				{
					FamilyInstance familyInstance = element as FamilyInstance;
					if (familyInstance.Symbol.Name == fiSymbol.Symbol.Name && familyInstance.Symbol.Family.Name == fiSymbol.Symbol.Family.Name)
					{
						list.Add(familyInstance);
					}
				}
			}
			return list;
		}
	}
}
